package com.synchronous7;
//懒汉式：延迟创建对象，第一次调用
//：延迟创建对象，第一次调用getInstance方法再创建对象
public class LazyOne {
    private static LazyOne instance;
    private LazyOne(){}
//    方式1：
    public static synchronized LazyOne getInstance1(){
        if (instance==null){
            instance = new LazyOne();
        }
        return instance;
    }
//    方式二：
    public static LazyOne getInstance2(){
        synchronized (LazyOne.class){
            if (instance == null){
                instance = new LazyOne();
            }
        }
        return instance;
    }
//    方式3：
    public static LazyOne getInstance3(){
        if (instance == null){
            synchronized (LazyOne.class){
                try {
                    Thread.sleep(10);//加这个代码，暴露问题
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                if (instance == null){
                    instance = new LazyOne();
                }
            }

        }
        return instance;
    }
//    注意：上述方式3中，有指令重排问题
//    volatile 关键字，避免指令重排


}
